var express = require('express');
var router = express.Router();

const MyQuery = require('../utils/db');
const timeStamp = require('time-stamp');



//文件上传
const formidable = require('formidable');
const path = require('path')
const fs = require('fs')
const { v4: uuidv4 } = require('uuid');



//引入配置文件
const { API_URL, verifyToken } = require('../utils/config')


router.get('/demo5', function(req, res, next) {
    res.send('个人中心模块')
});

//根据用户的id获取当前登录的用户信息,只是返回一条数据
router.get('/user', async(req, res, next) => {

    let { mid = '' } = req.query

    let data = {} //最终要返回的数据格式  msg,status,result
        //1. 写sql
    let sql = `select *,concat('${API_URL}/uploads/avatar/',head_photo_url) as head_photo_url from e_member  WHERE mid='${mid}'`
        //2. 执行sql
    let { result } = await MyQuery(sql) //{ err,result }

    if (result.length == 0) {
        data = {
            "msg": "查无此人",
            "status": 500
        }
        res.send(data)
        return;
    }

    delete result[0].password


    //3. 要处理成规范、格式化的json数据
    data = {
        msg: 'OK',
        status: 200,
        result: result[0] //只是返回一条数据
    }
    res.send(data);
})


//更新用户信息
router.put('/user', async(req, res, next) => {
    let { realname = '', sex = '', birthdate = '', city = '', mid = '' } = req.body;
    // res.send(req.body);
    let data = {};

    // if (realname == '' || sex == '' || birthdate == '' || city == '' || mid == '') {
    //     data = {
    //         "msg": "请传递必要参数",
    //         "status": 500
    //     }
    //     res.send(data);
    //     return;
    // }

    let sql = `select * from e_member where mid='${mid}'`;
    let { err, result } = await MyQuery(sql);

    if (result.length > 0) {
        sql = `update e_member set realname = '${realname}', sex = ${sex} ,  birthdate='${birthdate}' , city= '${city}' where mid = '${mid}'`;
        let { err, result: result2 } = await MyQuery(sql);
        console.log(result2);
        if (result2.affectedRows > 0) {
            data = {
                "msg": "OK",
                "status": 200
            }
            res.send(data);
        }
    }
});

//获取学习记录
router.get('/orders', async(req, res, next) => {
    let { mid = '' } = req.query;
    let data = {};

    if (mid == '') {
        data = {
            "msg": "无该学习记录",
            "status": 500
        };
        res.send(data);
        return;
    }
    let sql = `select ec.cid as cid,concat('${API_URL}/uploads/courses/',ec.image_src) as image_src,eo.oid as oid, ec.title as title,ec.price as price ,ec.subject_name as subject_name,ec.area_name as area_name,eo.createdate as createdate from e_course ec left join e_order eo on eo.cid = ec.cid where mid ='${mid}'`;
    let { err, result } = await MyQuery(sql);
    if (result.length > 0) {
        data = {
            "msg": "OK",
            "status": 200,
            result
        };
        res.send(data);
    }
});

//更新用户头像
router.post('/uploadhead', async(req, res, next) => {
    const form = formidable({
        uploadDir: 'temp'
    });

    form.parse(req, async(err, fields, files) => {
        // console.log(err, 'err为null则为证明没有错误');
        // console.log(fields, 'fields');
        // console.log(files, 'files');

        let oldpath = files.f.filepath
        let mid = fields.mid //用户的id

        let extname = path.extname(files.f.originalFilename) //获取扩展名
        let head_photo_url = uuidv4() + extname //图片的新名称
        let newPath = path.join('uploads/avatar', head_photo_url) //拼接后的新路径
        fs.renameSync(oldpath, newPath)

        let sql = `select * from e_member where mid = '${mid}'`;

        let { result } = await MyQuery(sql);
        if (result.length - 0 > 0) {
            let data = {};
            sql = `UPDATE e_member SET head_photo_url = '${head_photo_url}' WHERE mid='${mid}' `
            let { result: result2 } = await MyQuery(sql);
            console.log(result2);
            if (result2.affectedRows > 0) {
                data = {
                    msg: "OK",
                    status: 200,
                    result: `${API_URL}/uploads/avatar/${head_photo_url}`
                }
                res.send(data);
            }

        }
    });
});

module.exports = router;